package com.giw.uima;

import java.io.FileInputStream;
import java.io.IOException;

import java.util.Collections;
import java.util.List;

import org.apache.commons.io.IOUtils;

//import org.apache.uima.SimpleTokenAndSentenceAnnotator;
import org.apache.uima.TokenAnnotation;
import org.apache.uima.UimaContext;
import org.apache.uima.analysis_component.JCasAnnotator_ImplBase;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.Type;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import org.apache.uima.resource.ResourceInitializationException;
//import org.apache.uima.tagger.HMMTagger;
import org.apache.uima.util.Level;

public class NameAnnotator extends JCasAnnotator_ImplBase {

	private static final String PATH_DIZIONARIO = "dictionarypath";
	private static final String POS_FEATURENAME = "posTag";

	private List<String> namesList;

	// private HMMTagger hmm = new HMMTagger();
	public void initialize(UimaContext aContext)
			throws ResourceInitializationException {
		super.initialize(aContext);
		try {

			// hmm.initialize(aContext);
			namesList = IOUtils
					.readLines(new FileInputStream(String.valueOf(aContext
							.getConfigParameterValue(PATH_DIZIONARIO))));
			Collections.sort(namesList); // sort collection to make binary
											// search possible
		} catch (IOException e) {
			e.printStackTrace();
			aContext.getLogger().log(Level.SEVERE,
					"error reading dictionary file");
			throw new ResourceInitializationException(e);
		}
	}

	@Override
	public void process(JCas jcas) throws AnalysisEngineProcessException {
			for (Annotation annotation : jcas
				.getAnnotationIndex(TokenAnnotation.type)) {
			/*
			 * create a name annotation for each occurrence of a name in the
			 * dictionary
			 */

			if (Collections
					.binarySearch(namesList, annotation.getCoveredText()) >= 0
					&& isNP(annotation)) {
				NameAnnotation nameAnnotation = new NameAnnotation(jcas);
				nameAnnotation.setBegin(annotation.getBegin());
				nameAnnotation.setEnd(annotation.getEnd());
				nameAnnotation.addToIndexes();
			}
		}

	}

	private boolean isNP(Annotation annotation) {
		Type type = annotation.getType();
		String pos = annotation.getFeatureValueAsString(type
				.getFeatureByBaseName(POS_FEATURENAME));

		return pos != null && "np".equals(pos);
		// return true;
	}

}